'use strict';
const { Service } = require('egg');
const ModelName = 'LotteryRecord'
class RouterService extends Service {
  async getPage(where, page, pageSize) {
    return this.ctx.model[ModelName].findAndCountAll({
      where,
      offset: pageSize * (page - 1),
      limit: pageSize,
      order:[
        // id 降序
        ['created_at','DESC']
      ],
        include:[
            {
                model: this.ctx.model.User,
                as: 'user'
            },
            {
                model: this.ctx.model.Product,
                as: 'product'
            }
        ]
    });
  }
  // 所有列表
  async allList(where) {
    return this.ctx.model[ModelName].findAll({
      where,
      order:[
        // id 降序
        ['created_at','DESC']
      ],
        include:[
            {
                model: this.ctx.model.User,
                as: 'user'
            },
            {
                model: this.ctx.model.Product,
                as: 'product'
            }
        ]
    });
  }
  async findOne(id) {
    return this.ctx.model[ModelName].findOne({
      where: {
        id,
      },
    });
  }
  async create(data) {
    return this.ctx.model[ModelName].create(data);
  }
  async update(id, data) {
    return await this.ctx.model[ModelName].update(data, { where: { id } });
  }
  async deleteById(id) {
    return await this.ctx.model[ModelName].update({
        delete_flag: 1
    }, { where: { id } });
  }
    async initDailyLottery() {
        const today = new Date().toISOString().split('T')[0];
        const dailyLottery = await this.ctx.model.DailyLottery.findOne({ where: { date: today } });
        if (!dailyLottery) {
            await this.ctx.model.DailyLottery.create({ date: today, total: 0, count: 0 });
        }
    }
    async start(data) {
    const { user_id, record_id } = data;
    /**
     * 1. 中奖机率20%
     * 2. 每日奖项，获取product数据，每个产品每日的总数量为max_count
     */
    const { ctx } = this;
    const { model } = ctx;
    const { User, Product, LotteryRecord } = model;
    const user = await User.findOne({
        where: {
            id: user_id
        }
    })
    if (!user) {
        throw new Error('用户不存在');
    }
        await this.initDailyLottery();

        const today = new Date().toISOString().split('T')[0];
        const productList = await Product.findAll();
        // 每日中奖数量上限
        const maxcount = productList.reduce((acc, cur) => acc + cur.max_count, 0);
        const winProbability = 0.2; // 每日中奖概率（总体，不是每次抽奖的概率）

        // 获取当日的抽奖信息
        const dailyLottery = await this.ctx.model.DailyLottery.findOne({ where: { date: today } });
        const total = dailyLottery.total;
        const count = dailyLottery.count;

        // 检查是否还有中奖名额
        if (count >= maxcount) {
            throw new Error('今日中奖名额已满');
        }

        // 生成随机数并判断是否中奖
        const randomNum = Math.random(); // 生成一个0到1之间的随机数
        const isWinner = randomNum <= 0.2; // 判断是否中奖
        console.log(';randomNum',randomNum)
        // 更新数据库
        if (isWinner) {
            await dailyLottery.update({ count: count + 1, total: total + 1 });
        } else {
            await dailyLottery.update({ total: total + 1 });
        }
        await this.ctx.model.UserPracticeRecord.update({
            is_lottery: 1
        }, {
            where: {
                id: record_id
            }
        })
        // 返回本次中奖结果
        if (isWinner) {
            const insert = await LotteryRecord.create({
                user_id,
                record_id
            });
            // 更新用户的中奖记录id
            await user.update({ lottery_record_id: insert.id });

        }
        return {
            isWinner,
        }
    }

    async updateProduct(data) {
          const { lottery_record_id, product_id, user_id } = data;
          // 减库存
        const product = await this.ctx.model.Product.findOne({
            where: {
                id: product_id
            }
        })
        if (!product) {
            throw new Error('产品不存在');
        }
        if (product.count <= 0) {
            throw new Error('产品库存不足');
        }
        await product.update({
            count: product.count - 1
        },{
            where: {
                id: product_id
            }
        })
      // 更新领奖记录中的产品id
        await this.ctx.model[ModelName].update({
            product_id
        }, {
            where: {
                id: lottery_record_id
            }
        })
        // 更新用户的产品id
        await this.ctx.model.User.update({
            product_id
        },{
            where: {
               id: user_id
            }
        })
        return true
    }
}

module.exports = RouterService;
